package com.windy.dailynews.ui.fragment;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import com.windy.dailynews.R;
import com.windy.dailynews.model.Themes;
import com.windy.dailynews.presenter.SlideMenuContract;
import com.windy.dailynews.presenter.impl.SlideMenuPresenter;
import com.windy.dailynews.ui.activity.MainActivity;
import com.windy.dailynews.ui.adapter.SlideMenuAdapter;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by dingfeng on 2016/11/21.
 */
public class SlideFragment extends Fragment implements SlideMenuContract.View {
    private Activity mActivity;
    private SlideMenuContract.Presenter mPresenter;
    private SlideMenuAdapter mAdapter;
    private List<Themes> mThemeList;

    @Bind(R.id.listView)
    ListView mListView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_slide, container, false);
        ButterKnife.bind(this, view);
        init();
        return view;
    }

    private void init() {
        mActivity = getActivity();
        mThemeList = new ArrayList<>();
        Themes theme = new Themes();
        theme.setName("首页");
        theme.setId(0);
        mThemeList.add(theme);
        new SlideMenuPresenter(this);
        mPresenter.loadData();
    }

    @Override
    public void addMenu(List<Themes> list) {
        mThemeList.addAll(list);
        mAdapter = new SlideMenuAdapter(getContext(), mThemeList);
        mListView.setAdapter(mAdapter);
        mListView.setOnItemClickListener(onItemClickListener);
    }

    AdapterView.OnItemClickListener onItemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Fragment fragment;
            Themes theme = mThemeList.get(position);
            int themeId = theme.getId();
            if (themeId == 0) {
                fragment = MainFragment.newInstance();
            } else {
                fragment = ThemeNewsFragment.newInstance();
            }
            Bundle bundle = new Bundle();
            bundle.putInt("id", themeId);
            fragment.setArguments(bundle);
            getFragmentManager().beginTransaction().replace(R.id.content, fragment).commit();
            ((MainActivity)mActivity).closeDrawerLayout();

        }
    };

    @Override
    public void setPresenter(SlideMenuContract.Presenter presenter) {
        mPresenter = presenter;
    }

}
